<template>
  <div class="timesheet-container">
    <!-- 日历和表格区域 -->
    <div class="content-area">
      <!-- 左侧日历 -->
      <div :class="[true && 'calendar-section', isjinzhi && 'content-area-jinzhi']">
        <el-calendar
          v-model="currentDateqw"
          :first-day-of-week="1"
          @click="getlist(currentDateqw)"
        >
          <template #date-cell="{ data }">
            <p :class="getCellStyle(data.day as never)" style="line-height: 70px">
              {{ data.day.split("-").slice(2).join("-") }}
            </p>
          </template>
        </el-calendar>
      </div>

      <!-- 右侧工时表格 -->
      <div class="timesheet-section">
        <!-- loading组件 -->
        <div style="margin-bottom: 8px">
          <el-button type="primary" v-if="tijiaoflack" plain @click="tijiao"
            >提交审核</el-button
          >

          <el-button type="primary" v-if="tongguo" plain @click="tongyishenqing"
            >通过审批</el-button
          >

          <el-button type="danger" v-if="isshupman" plain @click="jujueshenqing"
            >退回审批</el-button
          >

          <!-- <el-button type="primary"  plain @click="deleteweekdata(currentDateqw)"
            >修改申请</el-button
          > -->
        </div>
        <div>
          <el-table v-loading="loading" :data="formattedData" border style="width: 100%">
            <el-table-column
              label="姓名"
              prop="username"
              width="80"
              v-if="!loading"
            ></el-table-column>

            <el-table-column label="类型" width="60" v-if="!loading">
              <template #default="scope">
                <div>
                  {{ scope.row.full_work == "1" ? "全职" : "兼职" }}
                </div>
              </template>
            </el-table-column>

            <!-- 动态生成列 -->
            <el-table-column
              v-for="day in weekDays"
              :key="day"
              :label="day"
              v-if="!loading"
            >
              <template #default="scope">
                <div
                  style="width: 100%; cursor: pointer; margin: 0 auto; padding: 0"
                  @click="handleClick(scope.row, day)"
                >
                  <div
                    v-if="getScheduleInfo(scope.row.scheduleMap, day)[1] == '无排班'"
                    :class="[
                      true && 'getScheduleInfostyle',
                      getScheduleInfo(scope.row.scheduleMap, day)[0] == '2' &&
                        'getScheduleInfostylecorlor',
                      getScheduleInfo(scope.row.scheduleMap, day)[0] == '1' &&
                        'paixiucoler',
                    ]"
                  >
                    {{ getScheduleInfo(scope.row.scheduleMap, day)[1] }}
                  </div>

                  <el-popover v-else placement="top" trigger="hover">
                    <el-button
                      type="danger"
                      size="small"
                      :disabled="isDeleteschedule(scope.row.scheduleMap, day)"
                      @click="deleteschedule(scope.row.scheduleMap, day)"
                      plain
                      >删除当前排班 ？</el-button
                    >
                    <template #reference>
                      <div
                        :class="[
                          true && 'getScheduleInfostyle',
                          getScheduleInfo(scope.row.scheduleMap, day)[0] == '2' &&
                            'getScheduleInfostylecorlor',
                          getScheduleInfo(scope.row.scheduleMap, day)[0] == '1' &&
                            'paixiucoler',
                        ]"
                      >
                        {{ getScheduleInfo(scope.row.scheduleMap, day)[1] }}
                      </div>
                    </template>
                  </el-popover>

                  <div>
                    <span :class="getdiaobo(scope.row.scheduleMap, day)[1]">{{
                      getdiaobo(scope.row.scheduleMap, day)[0]
                    }}</span>
                    <!-- <span
                      v-else-if="getdiaobo(scope.row.scheduleMap, day) == '1'"
                      class="diaoru"
                      >调入</span
                    >
                    <span
                      v-else-if="getdiaobo(scope.row.scheduleMap, day) == '2'"
                      class="diaochu"
                      >调出</span
                    > -->
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 班次修改弹框 -->
    <el-drawer
      v-if="dialogVisible"
      v-model="dialogVisible"
      size="520"
      :with-header="false"
    >
      <el-scrollbar height="100%">
        <div style="margin-bottom: 15px">
          <span style="font-size: 18px; font-weight: 600; margin-right: 8px">{{
            detailUserName
          }}</span>
          <span style="font-size: 18px; font-weight: 600; margin-right: 15px">{{
            heardtital
          }}</span>
          <span style="margin-bottom: 10px; font-weight: 600; margin-right: 8px"
            >所在门店：{{ inshopname }}</span
          >
        </div>
        <div style="margin-bottom: 10px">
          <span style="margin-right: 8px">调拨类型：“{{ in_outName }}”</span>
          <span>审核状态：“{{ flagname }}”</span>
        </div>

        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="110px"
          style="width: 100%; overflow: hidden; padding-right: 18px"
          :disabled="zhoujinzhi"
        >
          <div
            style="
              background-color: #ecf5ff;
              border-radius: 10px;
              overflow: hidden;
              padding-right: 6px;
              height: 50px;
              line-height: 50px;
              padding-left: 10px;
              margin-bottom: 10px;
            "
          >
            排班标记:
            <el-select
              v-model="formDataqw.tag_id"
              placeholder="请选择"
              style="width: 240px"
            >
              <el-option
                v-for="item in tagoptions"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>

          <div
            style="
              margin-bottom: 30px;
              background-color: #ecf5ff;
              border-radius: 10px;
              overflow: hidden;
              padding-right: 10px;
            "
            v-if="!showvaction"
          >
            <div
              style="
                margin-bottom: 12px;
                transform: translateX(6px);
                font-weight: 600;
                font-size: 15px;
                margin-top: 10px;
              "
              v-if="!kuabanone"
            >
              上下班时间段
              <span
                v-if="!zhoujinzhi"
                style="color: blue; cursor: pointer"
                @click="banciadds"
                >{{ !bancitow ? "添加" : "减少" }}</span
              >
            </div>
            <div
              style="margin-bottom: 12px; transform: translateX(20px); height: 30px"
              v-if="kuabanone"
            ></div>
            <div class="form-section">
              <div
                class="section-title"
                style="font-weight: 600; height: 30px; transform: translateX(20px)"
              >
                第1次上下班
              </div>
              <el-form-item label="上班时间" prop="onDutyTime">
                <el-time-select
                  v-model="formData.onDutyTime"
                  style="width: 50%"
                  start="00:15"
                  step="00:15"
                  end="23:50"
                  placeholder="start time"
                  @change="addaich(formData.onDutyTime)"
                />

                <span v-if="jiangehour != ''" style="transform: translateX(5%)"
                  >间隔{{ jiangehour }}</span
                >
              </el-form-item>
              <el-form-item label="下班时间" prop="offDutyTime">
                <el-time-select
                  v-model="formData.offDutyTime"
                  style="width: 50%"
                  start="00:15"
                  step="00:15"
                  end="23:50"
                  :clearable="false"
                  placeholder="end time"
                  @change="kuatianfun"
                />

                <span class="kuaban" v-if="kuabanone">次日</span>
                <div style="width: 50%; display: flex; justify-content: flex-end">
                  <el-checkbox
                    v-if="!bancitow"
                    v-model="kuabanone"
                    label="跨天"
                    size="large"
                    @change="kuatianfun"
                  />
                </div>
              </el-form-item>

              <div style="border-top: 1px solid #cdcdcd">
                <el-button
                  type="primary"
                  text
                  style="margin: 0 0 0 10px"
                  @click="zhongtuxiuxi"
                  >中途休息时间</el-button
                >
              </div>
              <el-form-item v-if="iszhongtu">
                <div
                  style="
                    display: flex;
                    justify-content: space-around;
                    margin-bottom: 10px;
                  "
                >
                  <el-time-picker
                    :clearable="false"
                    v-model="midwayBreak.start_break"
                    format="HH:mm"
                    placeholder="start time"
                    style="width: 40%"
                  />
                  <el-time-picker
                    :clearable="false"
                    v-model="midwayBreak.end_break"
                    format="HH:mm"
                    placeholder="end time"
                    style="width: 40%"
                  />
                </div>
              </el-form-item>

              <div style="border-top: 1px solid #cdcdcd" v-if="supplementTimebutton">
                <el-button
                  type="primary"
                  text
                  style="margin: 0 0 0 10px"
                  @click="supplementTime"
                  >补钟时间</el-button
                >
                <span v-if="supplementTimeflack" style="font-size: 15px"
                  >剩余：{{ buzhongcount }} 分钟</span
                >
              </div>
              <el-form-item v-if="supplementTimeflack" label="选项：">
                <div>
                  <el-radio-group v-model="supplementTimeData.buzhong_type">
                    <el-radio :value="1">晚到</el-radio>
                    <el-radio :value="2">早退</el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>

              <el-form-item v-if="supplementTimeflack" label="时长：">
                <div>
                  <el-input
                    :disabled="buzhongtypeflac"
                    v-model="supplementTimeData.buzhong_time"
                    type="number"
                    style="width: 80%"
                    placeholder="请输入时长"
                  /><span>分钟</span>
                </div>
              </el-form-item>
            </div>

            <div class="form-section" style="margin-top: 30px" v-if="bancitow">
              <div
                class="section-title"
                style="font-weight: 600; height: 30px; transform: translateX(20px)"
              >
                第2次上下班
              </div>
              <el-form-item label="上班时间" prop="onDutyTime2">
                <el-time-select
                  v-model="formData.onDutyTime2"
                  style="width: 50%"
                  start="00:15"
                  step="00:15"
                  end="23:50"
                  placeholder="start time"
                  @change="addaich2(formData.onDutyTime2)"
                />

                <span v-if="jiangehour2 != ''" style="transform: translateX(10%)"
                  >间隔{{ jiangehour2 }}</span
                >
              </el-form-item>
              <el-form-item label="下班时间" prop="offDutyTime2">
                <el-time-select
                  v-model="formData.offDutyTime2"
                  style="width: 50%"
                  start="00:15"
                  step="00:15"
                  end="23:50"
                  placeholder="start time"
                  :clearable="false"
                  @change="kuatianfun2"
                />

                <span class="kuaban" v-if="kuabanone2">次日</span>
                <div style="width: 50%; display: flex; justify-content: flex-end">
                  <el-checkbox
                    v-model="kuabanone2"
                    label="跨天"
                    size="large"
                    @change="kuatianfun2"
                  />
                </div>
              </el-form-item>

              <div>
                <el-button
                  type="primary"
                  text
                  style="margin: 0 0 0 10px"
                  @click="zhongtuxiuxi2"
                  >中途休息时间</el-button
                >
              </div>
              <el-form-item v-if="iszhongtu2">
                <div
                  style="
                    display: flex;
                    justify-content: space-around;
                    margin-bottom: 10px;
                  "
                >
                  <el-time-picker
                    :clearable="false"
                    v-model="midwayBreak.start_break2"
                    format="HH:mm"
                    placeholder="start time"
                    style="width: 40%"
                  />
                  <el-time-picker
                    :clearable="false"
                    v-model="midwayBreak.end_break2"
                    format="HH:mm"
                    placeholder="end time"
                    style="width: 40%"
                  />
                </div>
              </el-form-item>
            </div>
          </div>

          <div
            v-if="showvaction"
            style="
              background-color: #ecf5ff;
              border-radius: 10px;
              overflow: hidden;
              padding-right: 6px;
            "
          >
            <div class="form-section">
              <div class="form-section"></div>
              <div
                class="section-title"
                style="
                  margin-bottom: 12px;
                  transform: translateX(6px);
                  font-weight: 600;
                  margin-top: 10px;
                  font-size: 15px;
                "
              >
                请勾选休假原因
              </div>

              <el-form-item label="假期明细">
                <el-button type="primary" @click="vacationlog(true)" plain
                  >查看</el-button
                >
              </el-form-item>

              <el-form-item label="假期余额">
                <span style="margin-right: 20px" v-for="item in vacationyve">{{
                  `${item.leaveName} '${item.quota_num}' 天`
                }}</span>
              </el-form-item>

              <el-form-item label="假休原因" prop="vacationtype">
                <el-radio-group
                  size="small"
                  v-model="formData.vacationtype"
                  style="width: 100%"
                >
                  <el-radio
                    v-for="item in vacationyve"
                    :value="item.leave_code"
                    style="width: 40%"
                    >{{ item.leaveName }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            v-if="isVaction"
            plain
            style="position: absolute; left: 25px"
            @click="kongzhivocaion"
            :disabled="zhoujinzhi"
            >{{ showvaction ? "排班" : "排休" }}</el-button
          >
          <el-button @click="handlecancel">取消</el-button>
          <el-button :disabled="zhoujinzhi" type="primary" plain @click="handleSubmit"
            >保存</el-button
          >
        </div>
      </template>
    </el-drawer>

    <!-- 假期查看 -->
    <el-dialog
      v-model="dialogTableVisible"
      title="请选择假期类型查看"
      :close-on-click-modal="false"
      width="380"
    >
      <el-radio-group v-model="getVacationloglist" style="width: 100%">
        <el-radio
          v-for="item in vacationyve"
          :value="item.leave_code"
          style="width: 40%; display: inline-block"
          >{{ item.leaveName }}</el-radio
        >
      </el-radio-group>

      <el-table :data="vacationlogdata" style="width: 100%" height="230">
        <el-table-column label="假期周期">
          <template #default="scope">
            <span>{{ deteqiege(scope.row.years) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="假期余额">
          <template #default="scope">
            <span>{{ scope.row.numbers }} 天</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, reactive, onBeforeMount, watch } from "vue";
import { ElTable, ElTableColumn, ElButton, ElMessage, FormInstance } from "element-plus";
import {
  getscheduleList,
  unbdatascheduleList,
  putscheduleList,
  deleteransfer,
  vacationpost,
  getschedulemonth,
  delschedule,
  getKaoqinJiaban,
  getschedulWeek,
} from "@/api/schedulingManage";

import { getVacationlog } from "@/api/vacation";

import { getTagInfo } from "@/api/tag";

import "element-plus/dist/index.css";
import { number } from "echarts";

import { schedulingManageStore } from "@/stores/schedulingManage";
import { useRouter } from "vue-router";

import {
  schedulingManagetype,
  midwayBreaktype,
  vacationyvetype,
} from "@/types/schedulingManageTYpe";

import { formatDateToYearAndMonthDay } from "@/utils/date";

const router = useRouter();

const schedulingManageStoreData = schedulingManageStore();
const scheduledata = schedulingManageStoreData.getshopData();

//tag标记
interface TagOption {
  value?: any;
  label?: any;
}
const tagoptions = ref<TagOption[]>([]);

// 弹框
const dialogVisible = ref(false);

//日历禁止点击
const isjinzhi = ref(false);

// 加载值
const loading = ref(true);

//审批同意和拒绝按钮控制
const isshupman = ref(false);

const tongguo = ref(false);

//提交过则不显示按钮
// const delfalck = ref(false);

// // 提交为已经通过
// const checkInDates1 = ref([]);

// // 提交为待审核
// const checkInDates3 = ref([]);

// // 提交为拒绝
// const checkInDates4 = ref([]);

const MonthFlags: {
  [x: string]: any;
} = ref({});

// const WeekFlags: {
//   [x: string]: any;
// } = ref({});

// 首次加载需要的日期
const currentDateqw = ref(new Date());

const tijiaoflack = ref(false);

//查看假期日志
const dialogTableVisible = ref(false);
const getVacationloglist = ref("SHCODE");

const vacationuseridlog = ref("");
const vacationlogdata = ref();

const deteqiege = (val: {
  toString: () => {
    (): any;
    new (): any;
    length: number;
    slice: { (arg0: number, arg1: number): string; new (): any };
  };
}) => {
  let tate = "";
  let tates = "";
  let conute = "";
  if (val.toString().length == 4) {
    tate = val.toString().slice(0, 4);
    conute = `${tate}年`;
  } else {
    tate = val.toString().slice(0, 4);
    tates = val.toString().slice(4, val.toString().length);
    conute = `${tate}年${tates}月`;
  }
  return conute;
};

watch(getVacationloglist, (newval, olldval) => {
  getVacationloglist.value = newval;
  vacationlog(true);
});

const transformvacationlog = (data: { quota_cycle: any; quota_num: any }[]) =>
  data.map(({ quota_cycle, quota_num }) => ({
    years: quota_cycle,
    numbers: quota_num,
  }));

const vacationlog = async (val?: boolean) => {
  const res = await getVacationlog({
    leave_code: getVacationloglist.value,
    userid: vacationuseridlog.value,
  });

  vacationlogdata.value = transformvacationlog(res.data) || [];

  if (val) {
    dialogTableVisible.value = true;
  }
};

// 日历显示绿色
const getCellStyle = (date: never) => {
  if (MonthFlags.value[date]=='1') {
    return "signed-in1";
  }else if(MonthFlags.value[date]=='3'){
    return "signed-in3";
  }else if(MonthFlags.value[date]=='4'){
    return "signed-in4";
  }else{
    return " ";
  }

  // if (checkInDates1.value.includes(date)) {
  //   return "signed-in1";
  // } else if (checkInDates3.value.includes(date)) {
  //   return "signed-in3";
  // } else if (checkInDates4.value.includes(date)) {
  //   return "signed-in4";
  // } else {
  //   return " ";
  // }
};

// 日历选中发给后台的时间
const selecttoday = ref(" ");

// 获取当天的时间
onBeforeMount(() => {
  const aa = new Date();
  if (sessionStorage.getItem("gotoday")) {
    isjinzhi.value = true;
    currentDateqw.value = new Date(sessionStorage.getItem("gotoday") as string);
    selecttoday.value = sessionStorage.getItem("gotoday") as string;
  } else {
    selecttoday.value = formatDateToYearAndMonthDay(aa);
  }
});

// 没有信息时展示用于动态创建列表
const weekDays = ref([
  "星期天",
  "星期一",
  "星期二",
  "星期三",
  "星期四",
  "星期五",
  "星期六",
]);

// 格式化数据以便于在表格中显示
const formattedData = computed(() => {
  if (rawData.value.length > 0 && !(typeof rawData.value == "string")) {
    return (
      rawData.value?.map((item: any) => ({
        in_out: item.in_shop,
        userid: item.userid,
        full_work: item.full_work,
        username: item.username,
        scheduleMap: item.scheduleList.reduce((acc: any, cur: any) => {
          cur.userid = item.userid;
          acc[cur.week] = cur;
          return acc;
        }, {}),
      })) || []
    );
  } else {
    return [];
  }
});

// 排班信息的获取
const getformDatalist = async (val?: any) => {
  try {
    if (val) {
      loading.value = true;
      const aa = new Date(currentDateqw.value);
      selecttoday.value = formatDateToYearAndMonthDay(aa);
    }

    const response = await getscheduleList({
      shop_id: scheduledata.selfid,
      day: selecttoday.value,
    });

    if (response.code == "200") {
      if (val) {
        ElMessage.success("查询成功");
      }

      if (response.data.length > 0 && !(typeof response.data == "string")) {
        response.data[0].scheduleList.forEach(
          (element: { flag: string; day: string; week: any }, key: string | number) => {
            const as = element.day.toString();
            const aa = as.split(" ");
            const bb = aa[0].split("-");
            weekDays.value[key as number] = `${element.week} ${bb[0]}-${bb[1]}-${bb[2]}`;
          }
        );
      }

      if (val) {
        loading.value = false;
      }
    } else {
      if (val) {
        loading.value = false;
        ElMessage.error("查询失败");
      }
    }
    rawData.value = response.data;
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }
};

// 点击发送请求获取本周数据和30天的提交信息
const getlist = (val?: any) => {
  loading.value = true;
  // checkInDates1.value = [];
  // checkInDates3.value = [];
  // checkInDates4.value = [];
  MonthFlags.value = {};
  // WeekFlags.value = {};
  // checkuserId.value = [];

  //如果是点击日历
  if (val) {
    const newdate = new Date(currentDateqw.value);
    selecttoday.value = formatDateToYearAndMonthDay(newdate);
  }

  // console.log(formatDateToYearAndMonthDay(currentDateqw.value));

  nextTick(async () => {
    try {
      const RiLiData = await getschedulemonth({
        shop_id: scheduledata.selfid,
        month: selecttoday.value,
      });

      if (RiLiData.code == "200") {
        // RiLiData.data.forEach((item: { flag: string; day: any }) => {
        //   if (item.flag == "1") {
        //     checkInDates1.value.push(item.day as never);
        //   } else if (item.flag == "3") {
        //     checkInDates3.value.push(item.day as never);
        //   } else if (item.flag == "4") {
        //     checkInDates4.value.push(item.day as never);
        //   }
        // });
        RiLiData.data.forEach((item: { day: string; flag: any }) => {
          // 获取day的日期部分作为key
          const dayKey = item.day;
          MonthFlags.value[dayKey] = item.flag;
        });
      } else {
        console.error("日历flag查询失败");
      }

      // const ResWeekFlag = await getschedulWeek({
      //   shop_id: scheduledata.selfid,
      //   day: selecttoday.value,
      // });
      // if (ResWeekFlag.code == "200") {
      //   ResWeekFlag.data.forEach((item: { day: string; falg: any }) => {
      //     // 获取day的日期部分作为key
      //     const dayKey = item.day.split(" ")[0];
      //     WeekFlags.value[dayKey] = item.falg;
      //   });

      // } else {
      //   console.error("查询失败");
      // }


      const response = await getscheduleList({
        shop_id: scheduledata.selfid,
        day: selecttoday.value,
      });

      if (response.data.length > 0) {
        if (sessionStorage.getItem("gotoday")) {
          tijiaoflack.value = false;
          isshupman.value = true;
          if (sessionStorage.getItem("flag") == "1") {
            tongguo.value = false;
          } else {
            tongguo.value = true;
          }
        } else {
          if (response.data[0].is_manager == "1" || response.data[0].is_manager == "2") {
            tijiaoflack.value = true;
          } else {
            tijiaoflack.value = false;
          }
        }
      }

      yuanshidata.value = response.data;

      if (response.data.length > 0 && !(typeof response.data == "string")) {
        response.data[0].scheduleList.forEach(
          (
            element: { flag: string; day: string; userid: any; week: any },
            key: any 
          ) => {
            const as = element.day.toString();
            const aa = as.split(" ");
            const bb = aa[0].split("-");

            weekDays.value[key] = `${element.week} ${bb[0]}-${bb[1]}-${bb[2]}`;
          }
        );
      }

      rawData.value = response.data;

      loading.value = false;
    } catch (error) {
      console.error("Failed to fetch data:", error);
    }
    loading.value = false;
  });
};

// 存储从API获取的数据格式化
const rawData = ref([]);
// 原始数据
const yuanshidata = ref([]);

// 转换数据结构以适应 el-select，并且包含子项
const transformDepartmentList = (data: { id: any; name: any }[]) =>
  data.map(({ id, name }) => ({
    value: id,
    label: name,
  }));

// 在组件挂载时调用getlist函数
onMounted(async () => {
  getlist();
  const res = await getTagInfo();
  tagoptions.value = transformDepartmentList(res.data);
});

// 定义一个函数来检查工作时间是否超过9.5小时
function isWorkDurationOverEightHours(
  startTimeStr: any,
  endTimeStr: any,
  intervalHour: any
) {
  // 解析时间字符串为 Date 对象
  const parseTime = (timeStr: any) => new Date(timeStr);
  // 尝试解析输入的时间字符串
  const start = parseTime(startTimeStr);
  const end = parseTime(endTimeStr);
  // 检查日期是否有效

  // if (isNaN(start) || isNaN(end)) {
  //   ElMessage.error("无效的时间格式");
  //   return false;
  // }

  // 计算两个时间点之间的差异（以毫秒为单位）
  const durationMilliseconds = Number(end.getTime()) - Number(start.getTime());

  // 将毫秒转换为小时
  const durationInHours = durationMilliseconds / (1000 * 60 * 60);

  // 返回是否大于9.5小时的布尔值
  return durationInHours >= intervalHour;
}

// 当周数据提交按钮
const tijiao = async () => {
  // const datestr = selecttoday.value.toString().split("-");

  // const selectdata = `${datestr[0]}-${datestr[1].padStart(2, "0")}-${datestr[2].padStart(
  //   2,
  //   "0"
  // )}`;

  if (
    MonthFlags.value[selecttoday.value]=='1'||
    MonthFlags.value[selecttoday.value]=='3'

    // checkInDates1.value.includes(selecttoday.value as never) ||
    // checkInDates3.value.includes(selecttoday.value as never)
  ) {
    ElMessage({
      message: "当周数据已经提交不能再进行提交",
      type: "warning",
    });
  } else {
    try {
      const res = await putscheduleList({
        day: selecttoday.value,
        shop_id: scheduledata.selfid,
        flag: "3",
      });

      if (res.code == "200") {
        ElMessage.success("提交成功");
        getlist();
      } else {
        ElMessage.error("提交失败");
      }
    } catch (error) {
      console.error("Failed to fetch data:", error);
    }
  }
};

//同意审批
const tongyishenqing = async () => {
  try {
    const res = await putscheduleList({
      day: selecttoday.value,
      shop_id: scheduledata.selfid,
      flag: "1",
    });

    if (res.code == "200") {
      ElMessage.success("修改成功");
      // getlist();
      router.push("/SchedulingApprovals");
    } else {
      ElMessage.error("修改失败");
    }
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }
};

//拒绝审批
const jujueshenqing = async () => {
  try {
    const res = await putscheduleList({
      day: selecttoday.value,
      shop_id: scheduledata.selfid,
      flag: "4",
    });

    if (res.code == "200") {
      ElMessage.success("修改成功");
      // getlist();
      router.push("/SchedulingApprovals");
    } else {
      ElMessage.error("修改失败");
    }
  } catch (error) {
    console.error("Failed to fetch data:", error);
  }
};

// 获取特定日期的排班信息
const getScheduleInfo = (scheduleMap: any, day: any) => {
  const aa = day;
  const cc = aa.split(" ");
  let schedule = scheduleMap[cc[0]];

  if (schedule.rest_name) {
    return ["1", `排休 ${schedule.rest_name}`];
  } else {
    if (schedule.schedule_detail.length == 4) {
      const data1 = schedule.schedule_detail[0].check_time
        .toString()
        .split(" ")[1]
        .split(":");
      const data1str = `${data1[0]}:${data1[1]}`;
      const data2 = schedule.schedule_detail[1].check_time
        .toString()
        .split(" ")[1]
        .split(":");
      const data2str = `${data2[0]}:${data2[1]}`;

      const data3 = schedule.schedule_detail[2].check_time
        .toString()
        .split(" ")[1]
        .split(":");
      const data3str = `${data3[0]}:${data3[1]}`;
      const data4 = schedule.schedule_detail[3].check_time
        .toString()
        .split(" ")[1]
        .split(":");
      const data4str = `${data4[0]}:${data4[1]}`;

      return ["2", `${data1str}-${data2str} & ${data3str}-${data4str}`];
    } else if (schedule.schedule_detail.length == 2) {
      if (schedule.schedule_detail[0].check_time != "") {
        const data1 = schedule.schedule_detail[0].check_time
          .toString()
          .split(" ")[1]
          .split(":");
        const data1str = `${data1[0]}:${data1[1]}`;
        const data2 = schedule.schedule_detail[1].check_time
          .toString()
          .split(" ")[1]
          .split(":");
        const data2str = `${data2[0]}:${data2[1]}`;
        return ["2", `${data1str}-${data2str}`];
      } else {
        return ["0", "无排班"];
      }
    } else {
      return ["0", "无排班"];
    }
  }
};

// 返回信息用于展示调拨情况
const getdiaobo = (scheduleMap: any, day: any) => {
  if (scheduleMap[day.toString().split(" ")[0]].in_out == "1") {
    return ["调入", "diaoru"];
  } else if (scheduleMap[day.toString().split(" ")[0]].in_out == "2") {
    return ["调出", "diaochu"];
  } else {
    return ["正常", "zhengchang"];
  }
  // return scheduleMap[day.toString().split(" ")[0]].in_out;
};

// 弹框标题日期
const heardtital = ref("");

// 下面是抽屉相关的查值
// 第一次跨天
const kuabanone = ref(false);
// 第二次跨天
const kuabanone2 = ref(false);

// 添加班次
const bancitow = ref(false);

// 非全职人员中途休息时间
const midwayBreak: midwayBreaktype = reactive({
  start_break: "",
  end_break: "",
  start_break2: "",
  end_break2: "",
});

//防呆设计
const buzhongtypeflac = ref(true);

// 补卡时间点
const supplementTimeData = reactive({
  buzhong_type: "",
  buzhong_time: "",
});

watch(
  () => supplementTimeData.buzhong_type,
  (newval, olldval) => {
    if (newval != "" && newval != null && newval != undefined) {
      buzhongtypeflac.value = false;
    }
  }
);

//是否显示补种时间
const supplementTimeflack = ref(false);

//是否显示补种按钮
const supplementTimebutton = ref(false);

const buzhongcount = ref("0");

const parromas = reactive({
  userid: "",
  day: "",
});

const supplementTime = async () => {
  supplementTimeflack.value = !supplementTimeflack.value;
};

const iszhongtu = ref(false);
const iszhongtu2 = ref(false);

const zhongtuxiuxi = () => {
  midwayBreak.end_break = "";
  midwayBreak.start_break = "";
  iszhongtu.value = !iszhongtu.value;
};

const zhongtuxiuxi2 = () => {
  midwayBreak.end_break2 = "";
  midwayBreak.start_break2 = "";
  iszhongtu2.value = !iszhongtu2.value;
};

// 收集数据班次时间点
const formData = reactive({
  onDutyTime: "",
  offDutyTime: "",
  onDutyTime2: "",
  offDutyTime2: "",
  vacationtype: "",
});

// 要发送的数据
const formDataqw: schedulingManagetype = reactive({
  userid: "",
  shop_id: "",
  day: "",
  week: "",
  across: 0,
  section_num: "0",
  tag_id: "",
  buzhong_type: "",
  buzhong_time: "",
  schedule_detail: [
    {
      check_type: "OnDuty",
      check_time: "",
      number: 1,
    },
    {
      check_type: "OffDuty",
      check_time: "",
      number: 2,
    },
    {
      check_type: "OnDuty",
      check_time: "",
      number: 3,
    },
    {
      check_type: "OffDuty",
      check_time: "",
      number: 4,
    },
  ],
  is_rest: "",
  rest_type: "0",
});

// 抽屉取消按钮
const handlecancel = () => {
  supplementTimeflack.value = false;
  iszhongtu2.value = false;
  iszhongtu.value = false;
  dialogVisible.value = false;
  kuabanone.value = false;
  kuabanone2.value = false;
  bancitow.value = false;
  Object.assign(formData, {
    onDutyTime: "",
    offDutyTime: "",
    onDutyTime2: "",
    offDutyTime2: "",
    vacationtype: "",
  });
  Object.assign(midwayBreak, {
    start_break: "",
    end_break: "",
    start_break2: "",
    end_break2: "",
  });
  Object.assign(supplementTimeData, {
    buzhong_type: null,
    buzhong_time: null,
  });
};

// 添加班次
const banciadds = () => {
  bancitow.value = !bancitow.value;
  // 第二次班次时间
  kuabanone2.value = false;
  formData.onDutyTime2 = "";
  formData.offDutyTime2 = "";

  // 中途休息时间
  iszhongtu2.value = false;
  midwayBreak.end_break2 = "";
  midwayBreak.start_break2 = "";
};

// 表单校验规则
const rules = {
  onDutyTime: [{ required: true, message: "请选择上班时间", trigger: "change" }],
  offDutyTime: [{ required: true, message: "请选择下班时间", trigger: "change" }],
  onDutyTime2: [{ required: true, message: "请选择上班时间", trigger: "change" }],
  offDutyTime2: [{ required: true, message: "请选择下班时间", trigger: "change" }],
  vacationtype: [{ required: true, message: "请选择休假类型", trigger: "change" }],

  // start_break: [{ required: true, message: "请选择时间", trigger: "change" }],
  // end_break: [{ required: true, message: "请选择时间", trigger: "change" }],
  // start_break2: [{ required: true, message: "请选择时间", trigger: "change" }],
  // end_break2: [{ required: true, message: "请选择时间", trigger: "change" }],

  // start_leave_time: [{ required: true, message: "请选择时间", trigger: "change" }],
  // end_leave_time: [{ required: true, message: "请选择时间", trigger: "change" }],
};

// 验证选择时间的大小
const yanzhanegshijian = (valone: any, valtoe: any) => {
  const strq = valone + " ";
  const arrq = strq.split(":");
  const str1q = valtoe + " ";
  const arr1q = str1q.split(":");
  if (arrq[0] > arr1q[0]) {
    return true;
  } else if (arrq[0] == arr1q[0]) {
    if (arrq[1] > arr1q[1]) {
      return true;
    }
  }
  return false;
};

// 判断是否提交过从而禁止修改
const zhoujinzhi = ref(<boolean>false);

// 假期的控制所有信息!!!!!!!!!!!!!!!!!!!!!!!
const isVaction = ref(<boolean>false);
const showvaction = ref(<boolean>false);

const vacationyve: vacationyvetype = ref([]);

const kongzhivocaion = () => {
  formData.vacationtype = "";
  formDataqw.across = 0;
  showvaction.value = !showvaction.value;
};

// 如果full_work为0，则也不需要校验是否满足9.5个小时
const isfullwork = ref(false);

// 获取同一天的日期和判断是否跨天
function convertToToday(dateString: any, iskua?: any) {
  // 解析输入的日期字符串为 Date 对象
  const originalDate = new Date(dateString);
  // 检查是否是一个有效的日期
  if (isNaN(originalDate.getTime())) {
    throw new Error("无效的日期字符串");
  }

  // 获取当前日期
  const today = new Date(heardtital.value);
  let convertedDate = new Date(heardtital.value);
  // 构建新的 Date 对象，使用今天的日期和原始时间的时分秒
  if (iskua) {
    convertedDate = new Date(
      today.getFullYear(),
      today.getMonth(),
      today.getDate() + 1,
      originalDate.getHours(),
      originalDate.getMinutes(),
      originalDate.getSeconds(),
      originalDate.getMilliseconds()
    );
  } else {
    convertedDate = new Date(
      today.getFullYear(),
      today.getMonth(),
      today.getDate(),
      originalDate.getHours(),
      originalDate.getMinutes(),
      originalDate.getSeconds(),
      originalDate.getMilliseconds()
    );
  }
  return convertedDate;
}

// 时和分转时间对象
function parseTimeStringToDate(timeString: any) {
  // 验证输入是否匹配HH:mm格式
  const timePattern = /^(\d{1,2}):(\d{2})$/;
  const match = timeString.match(timePattern);

  if (!match) {
    throw new Error('时间格式不正确，请使用 "HH:mm" 格式');
  }

  // 解析小时和分钟
  const hours = parseInt(match[1], 10);
  const minutes = parseInt(match[2], 10);

  // 检查小时和分钟是否在合法范围内
  if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59) {
    throw new Error("非法时间值");
  }

  // 创建今天的日期对象，并将时间设为午夜

  let date = new Date(`${heardtital.value}`);

  date.setHours(0, 0, 0, 0); // 设置时间为00:00:00.000

  // 设置为提供的小时和分钟
  date.setHours(hours, minutes);

  return date;
}

const stater = ref("");

const vacationacc = ref([]);

const getvacationlogs = async (newval: string) => {
  const res = await getVacationlog({
    leave_code: newval,
    userid: vacationuseridlog.value,
  });
  vacationacc.value = res.data;
};

watch(
  () => formData.vacationtype,
  async (newval) => {
    getvacationlogs(newval);
  }
);

const detailUserName = ref("");

const flagname = ref("");
const inshopname = ref("");
const in_outName = ref("正常");
function in_outNamefun(val: any) {
  if (val == "0") {
    in_outName.value = "正常";
  } else if (val == "1") {
    in_outName.value = "调入";
  } else if (val == "2") {
    in_outName.value = "调出";
  }
}

// 点击事件处理函数
const handleClick = async (row: any, day: any) => {
  handlecancel();
  stater.value = "";
  in_outNamefun(row.scheduleMap[day.toString().split(" ")[0]].in_out);

  detailUserName.value = row.username;

  if (row.scheduleMap[day.toString().split(" ")[0]].flag == "1") {
    flagname.value = "已通过";
  } else if (row.scheduleMap[day.toString().split(" ")[0]].flag == "3") {
    flagname.value = "待审批";
  } else if (row.scheduleMap[day.toString().split(" ")[0]].flag == "4") {
    flagname.value = "已拒绝";
  } else {
    flagname.value = "未提交";
  }

  inshopname.value = row.scheduleMap[day.toString().split(" ")[0]].shop_name;

  //防呆设计
  buzhongtypeflac.value = true;
  //假期查询id
  vacationlog(false);
  vacationuseridlog.value = row.scheduleMap[day.toString().split(" ")[0]].userid;

  formDataqw.week = row.scheduleMap[day.toString().split(" ")[0]].week;
  stater.value = row.scheduleMap[day.toString().split(" ")[0]].in_out;
  formDataqw.tag_id = "";
  jiangehour.value = "";

  jiangehour2.value = "";

  showvaction.value = false;

  formDataqw.tag_id = row.scheduleMap[day.toString().split(" ")[0]].tag_id;

  heardtital.value = day.toString().split(" ")[1];

  //补钟
  parromas.day = row.scheduleMap[day.toString().split(" ")[0]].day;
  parromas.userid = row.scheduleMap[day.toString().split(" ")[0]].userid;

  // 排班回显
  if (row.scheduleMap[day.toString().split(" ")[0]].is_rest == 1) {
    // 请假回显
    showvaction.value = true;
    formData.vacationtype = row.scheduleMap[day.toString().split(" ")[0]].rest_type;
  } else {
    // 班次回显
    if (row.scheduleMap[day.toString().split(" ")[0]].buzhong_time != null) {
      supplementTimeData.buzhong_time =
        row.scheduleMap[day.toString().split(" ")[0]].buzhong_time;
      supplementTimeData.buzhong_type =
        row.scheduleMap[day.toString().split(" ")[0]].buzhong_type;
      supplementTimeflack.value = true;
    }

    if (row.scheduleMap[day.toString().split(" ")[0]].schedule_detail.length > 0) {
      if (row.scheduleMap[day.toString().split(" ")[0]].schedule_detail.length == 2) {
        if (
          row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[0].rest_time !=
            "" &&
          row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[0].rest_time !=
            undefined
        ) {
          midwayBreak.start_break = new Date(
            row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[0].rest_time
          );
          midwayBreak.end_break = new Date(
            row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[1].rest_time
          );
          iszhongtu.value = true;
        } else {
          iszhongtu.value = false;
        }

        if (row.scheduleMap[day.toString().split(" ")[0]].across == 1) {
          kuabanone.value = true;
        } else {
          kuabanone.value = false;
        }

        const check1 = row.scheduleMap[
          day.toString().split(" ")[0]
        ].schedule_detail[0].check_time
          .toString()
          .split(" ")[1]
          .split(":");

        formData.onDutyTime = `${check1[0]}:${check1[1]}`;

        const check2 = row.scheduleMap[
          day.toString().split(" ")[0]
        ].schedule_detail[1].check_time
          .toString()
          .split(" ")[1]
          .split(":");

        formData.offDutyTime = `${check2[0]}:${check2[1]}`;

        if (kuabanone.value) {
          calculateTimeDifference(
            parseTimeStringToDate(formData.onDutyTime),
            convertToToday(parseTimeStringToDate(formData.offDutyTime), 1)
          );
        } else {
          calculateTimeDifference(
            parseTimeStringToDate(formData.onDutyTime),
            convertToToday(parseTimeStringToDate(formData.offDutyTime))
          );
        }
      }
      if (row.scheduleMap[day.toString().split(" ")[0]].schedule_detail.length == 4) {
        bancitow.value = true;

        if (
          row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[0].rest_time !=
            "" &&
          row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[0].rest_time !=
            undefined
        ) {
          midwayBreak.start_break = new Date(
            row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[0].rest_time
          );
          midwayBreak.end_break = new Date(
            row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[1].rest_time
          );
          iszhongtu.value = true;
        } else {
          iszhongtu.value = false;
        }

        if (
          row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[2].rest_time !=
            "" &&
          row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[2].rest_time !=
            undefined
        ) {
          midwayBreak.start_break2 = new Date(
            row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[2].rest_time
          );
          midwayBreak.end_break2 = new Date(
            row.scheduleMap[day.toString().split(" ")[0]].schedule_detail[3].rest_time
          );
          iszhongtu2.value = true;
        } else {
          iszhongtu2.value = false;
        }

        if (row.scheduleMap[day.toString().split(" ")[0]].across == "1") {
          kuabanone2.value = true;
        } else {
          kuabanone2.value = false;
        }

        const check1 = row.scheduleMap[
          day.toString().split(" ")[0]
        ].schedule_detail[0].check_time
          .toString()
          .split(" ")[1]
          .split(":");

        formData.onDutyTime = `${check1[0]}:${check1[1]}`;

        const check2 = row.scheduleMap[
          day.toString().split(" ")[0]
        ].schedule_detail[1].check_time
          .toString()
          .split(" ")[1]
          .split(":");

        formData.offDutyTime = `${check2[0]}:${check2[1]}`;

        const check3 = row.scheduleMap[
          day.toString().split(" ")[0]
        ].schedule_detail[2].check_time
          .toString()
          .split(" ")[1]
          .split(":");

        formData.onDutyTime2 = `${check3[0]}:${check3[1]}`;

        const check4 = row.scheduleMap[
          day.toString().split(" ")[0]
        ].schedule_detail[3].check_time
          .toString()
          .split(" ")[1]
          .split(":");
        formData.offDutyTime2 = `${check4[0]}:${check4[1]}`;

        if (kuabanone.value) {
          calculateTimeDifference(
            parseTimeStringToDate(formData.onDutyTime),
            convertToToday(parseTimeStringToDate(formData.offDutyTime), 1)
          );
        } else {
          calculateTimeDifference(
            parseTimeStringToDate(formData.onDutyTime),
            convertToToday(parseTimeStringToDate(formData.offDutyTime))
          );
        }

        if (kuabanone2.value) {
          calculateTimeDifference2(
            parseTimeStringToDate(formData.onDutyTime2),
            convertToToday(parseTimeStringToDate(formData.offDutyTime2), 1)
          );
        } else {
          calculateTimeDifference2(
            parseTimeStringToDate(formData.onDutyTime2),
            convertToToday(parseTimeStringToDate(formData.offDutyTime2))
          );
        }
      }
    }
  }

  //是否全职
  if (row.full_work == 1) {
    isVaction.value = true;
    isfullwork.value = true;
    supplementTimebutton.value = true;
  } else {
    isVaction.value = false;
    isfullwork.value = false;
    supplementTimebutton.value = false;
  }

  //查询补钟额度
  const resbubu = await getKaoqinJiaban(parromas);
  if (resbubu.code == "200") {
    buzhongcount.value = resbubu.count;
  } else {
    console.error("补钟余额查询失败");
  }

  // 当周数据已经提交不能再进行修改
  if (
    row.scheduleMap[day.toString().split(" ")[0]].flag == "1" ||
    row.scheduleMap[day.toString().split(" ")[0]].flag == "3"
  ) {
    zhoujinzhi.value = true;
  } else {
    formDataqw.userid = row.userid;
    formDataqw.shop_id = row.scheduleMap["星期一"].shop_id;
    formDataqw.day = heardtital.value;

    if (row.in_out != undefined && row.in_out != null) {
      //调出人员日期
      if (row.in_out == "1") {
        if (row.scheduleMap[day.toString().split(" ")[0]].in_out == "2") {
          zhoujinzhi.value = true;
        } else {
          zhoujinzhi.value = false;
        }
      } else if (row.in_out == "0") {
        if (row.scheduleMap[day.toString().split(" ")[0]].in_out == "0") {
          zhoujinzhi.value = true;
        } else {
          zhoujinzhi.value = false;
        }
      }
    }
  }
  //修改表单显示
  dialogVisible.value = true;

  //假期请求
  try {
    const res = await vacationpost({
      userid: formDataqw.userid,
    });
    vacationyve.value = res.data;
  } catch (error) {
    console.error(error);
  }
};

// 表单校验
const formRef = ref<FormInstance>();

// const vacationquotacycle = ref("");

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) {
    return;
  }
  try {
    await formRef.value.validate();

    // 班次时间规则的校验
    if (!showvaction.value) {
      if (bancitow.value) {
        if (!kuabanone2.value) {
          if (
            yanzhanegshijian(formData.onDutyTime, formData.offDutyTime) ||
            yanzhanegshijian(formData.onDutyTime2, formData.offDutyTime2)
          ) {
            ElMessage.error("两个班次的下班时间都不能比上班时间早");
            return;
          }
          if (yanzhanegshijian(formData.offDutyTime, formData.onDutyTime2)) {
            ElMessage.error("第一次的下班时间不能比第二次上班时间早");
            return;
          }
        } else {
          if (yanzhanegshijian(formData.offDutyTime, formData.onDutyTime2)) {
            ElMessage.error("第一次上下班的下班时间不能比上班时间早");
            return;
          }
        }
      } else {
        if (!kuabanone.value) {
          if (yanzhanegshijian(formData.onDutyTime, formData.offDutyTime)) {
            ElMessage.error("下班时间不能比上班时间早");
            return;
          }
        }
      }

      //补钟校验
      if (supplementTimeflack.value) {
        if (
          supplementTimeData.buzhong_time == "" ||
          supplementTimeData.buzhong_type == "" ||
          supplementTimeData.buzhong_time == null ||
          supplementTimeData.buzhong_type == null
        ) {
          ElMessage.error("表单验证失败");
          return;
        }
        if (Number(supplementTimeData.buzhong_time) < 0) {
          ElMessage.error("补钟时长不能为负数");
          return;
        }

        if (supplementTimeData.buzhong_time > buzhongcount.value) {
          ElMessage.error("补钟时长不能大于剩余额度");
          return;
        }
        if (Number(supplementTimeData.buzhong_time) >= 570) {
          ElMessage.error("补钟时间不能超过9.5个小时");
          return;
        }
      }

      // 判断是否跨班然后日期加1
      const formattedDate = function (kua?: any) {
        let ri = 12;
        if (kua == 1) {
          ri = ri + 1;
        }
        return `${2025}-${10}-${ri}`;
      };
      const onedate = `${formattedDate(0)} ${formData.onDutyTime}:00`;
      const towdate = ref("");
      if (kuabanone.value) {
        towdate.value = `${formattedDate(1)} ${formData.offDutyTime}:00`;
      } else {
        towdate.value = `${formattedDate(0)} ${formData.offDutyTime}:00`;
      }

      if (isfullwork.value) {
        if (!isWorkDurationOverEightHours(onedate, towdate.value, 9.5)) {
          ElMessage.warning("全职员工当天排班时间不能小于9.5个小时");
          return;
        }
      }
    }

    //赋值传值
    if (!showvaction.value) {
      formDataqw.schedule_detail = [
        {
          check_type: "OnDuty",
          check_time: "",
          number: 1,
        },
        {
          check_type: "OffDuty",
          check_time: "",
          number: 2,
        },
        {
          check_type: "OnDuty",
          check_time: "",
          number: 3,
        },
        {
          check_type: "OffDuty",
          check_time: "",
          number: 4,
        },
      ];

      if (!bancitow.value) {
        formDataqw.schedule_detail[0].check_time = `${heardtital.value} ${formData.onDutyTime}:00`;
        formDataqw.schedule_detail[1].check_time = `${heardtital.value} ${formData.offDutyTime}:00`;
        formDataqw.section_num = "1";

        if (iszhongtu.value) {
          formDataqw.schedule_detail[0].rest_time = `${
            heardtital.value
          } ${getHoursAndMinutes(midwayBreak.start_break)}:00`;
          formDataqw.schedule_detail[1].rest_time = `${
            heardtital.value
          } ${getHoursAndMinutes(midwayBreak.end_break)}:00`;
        } else {
          delete formDataqw.schedule_detail[0].rest_time;
          delete formDataqw.schedule_detail[1].rest_time;
        }

        // 补钟
        if (supplementTimeflack.value) {
          formDataqw.buzhong_time = supplementTimeData.buzhong_time;
          formDataqw.buzhong_type = supplementTimeData.buzhong_type;
        } else {
          delete formDataqw.buzhong_time;
          delete formDataqw.buzhong_type;
        }

        formDataqw.schedule_detail.splice(2, 2);
        // 跨天
        if (kuabanone.value) {
          formDataqw.across = "1";
        } else {
          formDataqw.across = "0";
        }
      } else if (bancitow.value) {
        formDataqw.schedule_detail.push(
          {
            check_type: "OnDuty",
            check_time: "",
            number: 3,
          },
          {
            check_type: "OffDuty",
            check_time: "",
            number: 4,
          }
        );

        formDataqw.schedule_detail[0].check_time = `${heardtital.value} ${formData.onDutyTime}:00`;
        formDataqw.schedule_detail[1].check_time = `${heardtital.value} ${formData.offDutyTime}:00`;
        formDataqw.schedule_detail[2].check_time = `${heardtital.value} ${formData.onDutyTime2}:00`;
        formDataqw.schedule_detail[3].check_time = `${heardtital.value} ${formData.offDutyTime2}:00`;

        formDataqw.section_num = "2";
        if (kuabanone2.value) {
          formDataqw.across = "1";
        } else {
          formDataqw.across = "0";
        }

        if (iszhongtu.value) {
          formDataqw.schedule_detail[0].rest_time = `${
            heardtital.value
          } ${getHoursAndMinutes(midwayBreak.start_break)}:00`;
          formDataqw.schedule_detail[1].rest_time = `${
            heardtital.value
          } ${getHoursAndMinutes(midwayBreak.end_break)}:00`;
        } else {
          delete formDataqw.schedule_detail[0].rest_time;
          delete formDataqw.schedule_detail[1].rest_time;
        }

        // 补钟
        if (supplementTimeflack.value) {
          formDataqw.buzhong_time = supplementTimeData.buzhong_time;
          formDataqw.buzhong_type = supplementTimeData.buzhong_type;
        } else {
          delete formDataqw.buzhong_time;
          delete formDataqw.buzhong_type;
        }

        if (iszhongtu2.value) {
          formDataqw.schedule_detail[2].rest_time = `${
            heardtital.value
          } ${getHoursAndMinutes(midwayBreak.start_break2)}:00`;
          formDataqw.schedule_detail[3].rest_time = `${
            heardtital.value
          } ${getHoursAndMinutes(midwayBreak.end_break2)}:00`;
        } else {
          delete formDataqw.schedule_detail[2].rest_time;
          delete formDataqw.schedule_detail[3].rest_time;
        }

        formDataqw.schedule_detail.splice(4, 2);
      }
    } else {
      for (const item of vacationyve.value) {
        if (item.leave_code == formData.vacationtype) {
          if (item.quota_num <= 0) {
            ElMessage.warning("假期余额为0不能再休假");
            return;
          }
        }
      }
    }

    if (formData.vacationtype) {
      formDataqw.schedule_detail = [];
      formDataqw.is_rest = "1";
      formDataqw.section_num = "0";
      formDataqw.rest_type = formData.vacationtype;
      delete formDataqw.buzhong_time
      delete formDataqw.buzhong_type
    } else {
      formDataqw.is_rest = "0";
      formDataqw.rest_type = "";
    }

    formDataqw.shop_id = scheduledata.selfid;

    const res = await unbdatascheduleList(formDataqw);

    if (res.code == "200") {
      ElMessage.success("保存成功");
      getformDatalist();

      handlecancel();
      dialogVisible.value = false;
    } else {
      ElMessage.error("保存失败");
    }
  } catch (error) {
    ElMessage.error("表单验证失败");
    console.error("表单验证失败:", error);
  }
};

//排班删除
const deleteschedule = async (row: any, day: any) => {
  try {
    const res = await delschedule({
      userid: row[day.toString().split(" ")[0]].userid,
      day: row[day.toString().split(" ")[0]].day,
      shop_id: row[day.toString().split(" ")[0]].shop_id,
    });

    if (res.code == "200") {
      ElMessage.success("排班删除成功");
      getformDatalist();
    } else {
      ElMessage.error("排班删除失败");
    }
  } catch (error) {
    console.error(error);
  }
};

// 控制排班删除按钮
const isDeleteschedule = (row: any, day: any) => {

  if (
    row[day.toString().split(" ")[0]].in_out == '2'||
    // WeekFlags.value[row[day.toString().split(" ")[0]].day]=='1' ||
    // WeekFlags.value[row[day.toString().split(" ")[0]].day]=='3'||

    MonthFlags.value[selecttoday.value]=='1'||
    MonthFlags.value[selecttoday.value]=='3'
    // checkInDates1.value.includes(row[day.toString().split(" ")[0]].day as never) ||
    // checkInDates3.value.includes(row[day.toString().split(" ")[0]].day as never)
  ) {
    return true;
  } else {
    return false;
  }
};

// Date对象转时和分
function getHoursAndMinutes(date: any) {
  if (!(date instanceof Date)) {
    throw new TypeError("传入的参数必须是 Date 对象");
  }

  // 获取小时和分钟
  let hours: any = date.getHours();
  let minutes: any = date.getMinutes();

  // 格式化为两位数
  hours = String(hours).padStart(2, "0");
  minutes = String(minutes).padStart(2, "0");

  let timehh: any = "00";
  if (minutes !== "00") {
    timehh = Number(minutes);
  }

  // 返回格式化的字符串
  return `${hours}:${timehh}`;
}

// 跨天得单独计算
function kuatianfun() {
  if (kuabanone.value) {
    calculateTimeDifference(
      parseTimeStringToDate(formData.onDutyTime),
      convertToToday(parseTimeStringToDate(formData.offDutyTime), 1)
    );
  } else {
    calculateTimeDifference(
      parseTimeStringToDate(formData.onDutyTime),
      convertToToday(parseTimeStringToDate(formData.offDutyTime))
    );
  }
}

// 跨天得单独计算
function kuatianfun2() {
  if (kuabanone2.value) {
    calculateTimeDifference2(
      parseTimeStringToDate(formData.onDutyTime2),
      convertToToday(parseTimeStringToDate(formData.offDutyTime2), 1)
    );
  } else {
    calculateTimeDifference2(
      parseTimeStringToDate(formData.onDutyTime2),
      convertToToday(parseTimeStringToDate(formData.offDutyTime2))
    );
  }
}

//设置间隔得时间单位小时如9、9.5
const jiangehour = ref("");
// 计算间隔小时
function calculateTimeDifference(date1: any, date2: any) {
  // 检查输入是否为有效的 Date 对象
  if (!(date1 instanceof Date) || !(date2 instanceof Date)) {
    return;
  }

  // 计算两个日期之间的差异，以毫秒为单位
  const differenceMs = Number(date2) - Number(date1);

  // 将毫秒转换为天、小时、分钟
  const days = Math.floor(differenceMs / (1000 * 60 * 60 * 24));
  const hours = Math.floor((differenceMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  let minutes = Math.floor((differenceMs % (1000 * 60 * 60)) / (1000 * 60));
  jiangehour.value = "";

  // 确定符号，如果 differenceMs 是负数则结果也是负数
  const sign = differenceMs < 0 ? " -" : "";
  if (minutes == 29) {
    minutes = 30;
  }

  // 返回格式化的字符串
  jiangehour.value = `${days}天${sign} ${String(Math.abs(hours)).padStart(
    2,
    "0"
  )}小时 ${String(Math.abs(minutes)).padStart(2, "0")}分钟`;
}

const jiangehour2 = ref("");
// 计算间隔小时
function calculateTimeDifference2(date1: any, date2: any) {
  // 检查输入是否为有效的 Date 对象
  if (!(date1 instanceof Date) || !(date2 instanceof Date)) {
    return;
  }
  // 计算两个日期之间的差异，以毫秒为单位
  const differenceMs = Number(date2) - Number(date1);
  // 将毫秒转换为天、小时、分钟
  const days = Math.floor(differenceMs / (1000 * 60 * 60 * 24));
  const hours = Math.floor((differenceMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  let minutes = Math.floor((differenceMs % (1000 * 60 * 60)) / (1000 * 60));
  jiangehour2.value = "";
  // 确定符号，如果 differenceMs 是负数则结果也是负数
  const sign = differenceMs < 0 ? " -" : "";
  if (minutes == 29) {
    minutes = 30;
  }

  // 返回格式化的字符串
  jiangehour2.value = `${days}天${sign} ${String(Math.abs(hours)).padStart(
    2,
    "0"
  )}小时 ${String(Math.abs(minutes)).padStart(2, "0")}分钟`;
}

// 判断是否跨天和往后加9.5个小时
function addaich(timeString: any) {
  jiangehour.value = "";
  if (timeString != undefined) {
    const [hours, minutes] = timeString.split(":").map(Number);
    // 创建一个新的日期对象，设置时间为午夜（今天的00:00）
    let date = new Date(heardtital.value);
    // 记录当前的日期
    const originalDate = date.getDate();
    date.setHours(0, 0, 0, 0); // 设置为今天的00:00

    // 设置为给定的时间加30分钟
    date.setHours(hours, minutes + 30, 0, 0);

    // 添加9小时
    date.setHours(date.getHours() + 9);

    // 检查添加9小时后的日期是否变化了
    const hasCrossedDay = originalDate !== date.getDate();

    formData.offDutyTime = getHoursAndMinutes(date);

    if (hasCrossedDay) {
      bancitow.value = false;
      kuabanone.value = hasCrossedDay;
      formData.onDutyTime2 = "";
      formData.offDutyTime2 = "";
    } else {
      kuabanone.value = false;
    }
    kuatianfun();
  } else {
    formData.offDutyTime = "";

    kuabanone.value = false;
  }
}
// 判断是否跨天和往后加9.5个小时
function addaich2(timeString: any) {
  if (timeString != undefined) {
    const [hours, minutes] = timeString.split(":").map(Number);
    // 创建一个新的日期对象，设置时间为午夜（今天的00:00）
    let date = new Date(heardtital.value);
    // 记录当前的日期
    const originalDate = date.getDate();
    date.setHours(0, 0, 0, 0); // 设置为今天的00:00

    // 设置为给定的时间加30分钟
    date.setHours(hours, minutes + 30, 0, 0);

    // 添加9小时
    date.setHours(date.getHours() + 9);

    // 检查添加9小时后的日期是否变化了
    const hasCrossedDay = originalDate !== date.getDate();

    formData.offDutyTime2 = getHoursAndMinutes(date);

    if (hasCrossedDay) {
      kuabanone2.value = hasCrossedDay;
    } else {
      kuabanone2.value = false;
    }

    kuatianfun2();
  } else {
    formData.offDutyTime2 = "";

    kuabanone2.value = false;
  }
}
</script>

<style scoped lang="scss">
.getScheduleInfostyle {
  width: 100%;
  height: 50px;
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.getScheduleInfostylecorlor {
  color: #b69510;
}

.paixiucoler {
  color: #009107;
}

.diaoru {
  display: block;
  width: 50px;
  background-color: #fef6d5;
  border-radius: 5px;
  margin: 0 auto;
}

.zhengchang {
  display: block;
  width: 50px;
  background-color: #56bc5b;
  border-radius: 5px;
  margin: 0 auto;
}

.diaochu {
  display: block;
  width: 50px;
  background-color: #e96725;
  border-radius: 5px;
  margin: 0 auto;
}

.wustyle {
  display: block;
  width: 50px;
  background-color: #c0c4cc;
  border-radius: 5px;
  margin: 0 auto;
}

.el-radio {
  width: 50px;
}

.kuaban {
  position: absolute;
  top: 8px;
  left: 52%;
  border-radius: 8px;
  background-color: #fff0f0;
  border: 1px solid red;
  color: red;
  display: inline-block;
  width: 40px;
  text-align: center;
  line-height: 24px;
  height: 25px;
}

.signed-in1 {
  border-radius: 3px;
  overflow: hidden;
  display: inline-block;
  text-align: center;
  width: 100%;
  height: 100%;
  background-color: rgb(86, 139, 86) !important;
  color: white;
  cursor: not-allowed;
}

.signed-in3 {
  border-radius: 3px;
  overflow: hidden;
  display: inline-block;
  text-align: center;
  width: 100%;
  height: 100%;
  background-color: #ceb753 !important;
  color: white;
  cursor: not-allowed;
}

.signed-in4 {
  border-radius: 3px;
  overflow: hidden;
  display: inline-block;
  text-align: center;
  width: 100%;
  height: 100%;
  background-color: #e96725 !important;
  color: white;
  cursor: not-allowed;
}

.timesheet-container {
  padding: 20px;
  background: #fff;

  .content-area-jinzhi {
    cursor: not-allowed;
    pointer-events: none;
  }

  .content-area {
    display: flex;
    gap: 20px;

    .calendar-section {
      flex: 0 0 320px;

      :deep(.el-calendar) {
        border: 1px solid #dcdfe6;
        border-radius: 4px;
      }
    }

    .timesheet-section {
      flex: 1;

      :deep(.el-input-number) {
        width: 100%;
      }
    }
  }
}

body {
  margin: 0;
}

.timesheet-section {
  .el-table {
    :deep(.el-table__header) {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 500;
        text-align: center;
      }
    }

    :deep(.el-table__body) {
      td {
        text-align: center;
      }
    }
  }

  .el-input-number {
    width: 100%;
  }
}

.balance-dialog {
  :deep(.el-dialog__header) {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }

    .el-dialog__close {
      font-size: 18px;
      color: #909399;
    }
  }

  :deep(.el-dialog__body) {
    padding: 24px 20px;
  }

  :deep(.el-dialog__footer) {
    padding: 16px 20px;
    border-top: 1px solid #dcdfe6;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;

  .el-button {
    padding: 8px 20px;
    min-width: 80px;
    height: 32px;
    line-height: 1;
  }
}

.card-content {
  p {
    span:first-child {
      margin-right: 6px;
    }
  }
}
</style>
